package cn.monkey.service.impl;

import cn.monkey.mapper.MenuMapper;
import cn.monkey.mapper.UserMapper;
import cn.monkey.pojo.Menu;
import cn.monkey.pojo.Role;
import cn.monkey.pojo.User;
import cn.monkey.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    MenuMapper mapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,username);
        User user = userMapper.selectOne(queryWrapper);
        if(user==null){
            throw new UsernameNotFoundException("账号或密码错误");
        }
        List<Role> roles = userMapper.getRoleNamesByuid(user.getUid());
        user.setRoles(roles);
        List<String> roleNames = roles.stream().map(Role::getName).toList();
        user.setAuthorities(AuthorityUtils.createAuthorityList(roleNames));
        List<Long> roleIds = roles.stream().map(Role::getRid).toList();
        List<Menu> menus = mapper.getMenusByRoleId(roleIds);
        user.setMenus(menus);
        return user;
    }
}
